import json
import random
import re
from datetime import datetime

from info.utils.response_code import RET
from . import passport_blue
from ...constants import IMAGE_CODE_REDIS_EXPIRES, SMS_CODE_REDIS_EXPIRES
from ...utils.captcha.captcha import captcha
from info import redis_store, db
from flask import request, make_response, current_app, jsonify, session
from info.models import  User

# 图片验证码
@passport_blue.route("/image_code")
def image_code():
    # data是二进制
    name, code, image_data = captcha.generate_captcha()
    cur_id = request.args.get("cur_id")
    pre_id = request.args.get("pre_id")
    try:
        # 将验证码存入redis
        redis_store.set("image_code:%s" % cur_id, code, IMAGE_CODE_REDIS_EXPIRES)
        # 删除上一次验证码
        if pre_id:
            redis_store.delete("image_code:%s" % pre_id)
    except Exception as e:
        current_app.logger.error(e)
    respose = make_response(image_data)
    respose.headers["content-type"] = "image/png"
    return respose


# 短信验证码
@passport_blue.route("/sms_code", methods=["POST"])
def phone_code():
    json_data = request.json
    mobile = json_data.get("mobile")
    image_code = json_data.get("image_code")
    image_code_id = json_data.get("image_code_id")
    print(json_data)
    if not all([mobile, image_code_id, image_code]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数不全")
    try:
        redis_image_code = redis_store.get("image_code:%s" % image_code_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="redis操作失败")
    if not redis_image_code:
        return jsonify(errno=RET.NODATA, errmsg="验证码过期")

    if redis_image_code.upper() != image_code.upper():
        return jsonify(errno=RET.DATAERR, errmsg="图片验证码不正确")
    if not re.match(r"^1(3[0-9]|5[0-3,5-9]|7[1-3,5-8]|8[0-9])\d{8}$", mobile):
        return jsonify(errno=RET.PHONERR, errmsg="手机格式不正确")
    try:
        redis_store.delete("image_code:%s" % image_code_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="redis删除操作失败")
    # 生成短信验证码
    sms_code = random.randint(1000, 9999)
    print("短信验证码为", sms_code)
    try:
        redis_store.set("sms_code:%s" % mobile, sms_code, SMS_CODE_REDIS_EXPIRES)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="手机验证码存入redis操作失败")
    return jsonify(errno=RET.OK, errmsg="短信发送成功")


# 注册
@passport_blue.route("/register", methods=["POST"])
def register():
    json_data = request.json
    mobile = json_data.get("mobile")
    sms_code = json_data.get("sms_code")
    password = json_data.get("password")
    if not all([mobile, sms_code, password]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数不全")
    try:
        sms_code = redis_store.get("sms_code:%s" % mobile)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="redis查询失败")
    # 判断验证码是否正确
    if sms_code != sms_code:
        return jsonify(errno=RET.DBERR, errmsg="验证码不正确")

    try:
        redis_store.delete("sms_code:%s" % mobile)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="redis删除验证码失败")
    user=User()
    user.nick_name=mobile
    user.password=password
    user.mobile=mobile
    user.signature="该用户什么都没写"
    try:
        db.session.add(user)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        print(e)
        return jsonify(errno=RET.DBERR,errmsg="保存用户失败")
    return jsonify(errno=RET.OK,errmsg="注册成功")

#登录接口
@passport_blue.route("/login",methods=["POST"])
def login():
    mobile=request.json.get("mobile")
    password=request.json.get("password")
    if not all([mobile,password]):
        return  jsonify(errno=RET.PARAMERR,errmsg="参数不全")
    try:
        user=User.query.filter(User.mobile==mobile).first()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg="user查询失败")
    print(user)
    if not user:
        return  jsonify(errno=RET.NODATA,errmsg="查询为空")

    if not user.check_passowrd(password):
        return  jsonify(errno=RET.DATAERR,errmsg="密码错误")
    session["user_id"]=user.id
    user.last_login=datetime.now()
    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
    print("登录测试")
    return  jsonify(errno=RET.OK,errmsg="登录成功")

#退出
@passport_blue.route("/logout",methods=["POST"])
def logout():
    session.pop("user_id",None)

    return jsonify(errno=RET.OK,errmsg="退出成功")